package com.michael.demo.springcloud.alibaba.seata.api.controller;

import com.michael.demo.springcloud.alibaba.seata.api.feign.service.OrderSrvice;
import com.michael.demo.springcloud.alibaba.seata.api.feign.service.StorageSrvice;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * 类功能描述:
 * <pre>
 *   xxxx
 * </pre>
 *
 * @author Michael
 * @version 1.0
 * @date 2021/04/02 11:45
 */
@RestController
@RequestMapping("/order")
public class BizController {

    @Autowired
    private StorageSrvice storageSrvice;
    @Autowired
    private OrderSrvice orderSrvice;

    private static final String SUCCESS = "SUCCESS";

    public static final String code = "TS0099";
    public static final Integer count = 2;
    public static final Long userId = 10000L;

    @GlobalTransactional(timeoutMills = 300000, name = "default")
    @GetMapping("/make")
    public String makeOrderTest() {

        //storageSrvice.test1("abc", "def");
        //storageSrvice.test2("abc", 111);
        //storageSrvice.test3("abc", "def");
        //storageSrvice.test4("abc", 111);

        // 1. 扣减库存
        String result = storageSrvice.deduct(code, count);


        if (!SUCCESS.equals(result)) {
            throw new RuntimeException();
        }

        // 2. 保存订单
        result = orderSrvice.order(userId, code, count);

        if (!SUCCESS.equals(result)) {
            throw new RuntimeException();
        }

        //Random random = new Random();
        //if (random.nextBoolean()) {
        //    throw new RuntimeException("BizController 模拟异常");
        //}

        return SUCCESS;
    }
}
